package org.Lin.dao;

import org.Lin.model.FriendMessage;
import org.Lin.util.DatabaseUtil;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class FriendMessageDAO {

    public void insert(FriendMessage message) throws SQLException {
        String sql = "INSERT INTO FriendMessage(sender_id, receiver_id, message_data) VALUES (?, ?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, message.getSenderId());
            stmt.setInt(2, message.getReceiverId());
            stmt.setString(3, message.getMessageData());
            stmt.executeUpdate();
        }
    }

    public List<FriendMessage> findBySenderAndReceiver(int senderId, int receiverId) throws SQLException {
        List<FriendMessage> messages = new ArrayList<>();
        String sql = "SELECT * FROM FriendMessage WHERE sender_id = ? AND receiver_id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, senderId);
            stmt.setInt(2, receiverId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                messages.add(mapToMessage(rs));
            }
        }
        return messages;
    }

    private FriendMessage mapToMessage(ResultSet rs) throws SQLException {
        FriendMessage msg = new FriendMessage();
        msg.setID(rs.getInt("ID"));
        msg.setSenderId(rs.getInt("sender_id"));
        msg.setReceiverId(rs.getInt("receiver_id"));
        msg.setMessageData(rs.getString("message_data"));
        msg.setSentTime(rs.getObject("sent_time", LocalDateTime.class));
        msg.setMessageStatus(rs.getString("message_status"));
        return msg;
    }
}
